package com.jack.xiaoer.web.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jack.xiaoer.dto.AccountDTO;
import com.jack.xiaoer.dto.CartDTO;
import com.jack.xiaoer.util.AjaxResponse;
import com.jack.xiaoer.util.JWTUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Jackaroo Zhang on 2018/12/19.
 */
public class AuthorizationInterceptor implements HandlerInterceptor {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        String userIdStr = request.getHeader("userId");

        if (StringUtils.isBlank(token) || StringUtils.isBlank(userIdStr)) {
            AjaxResponse error = AjaxResponse.invalid("token和userId都不能为空");
            handleIfFail(error, response);
            return false;
        }

        Long userId = Long.parseLong(userIdStr);
        AccountDTO accountDTO = JWTUtil.verifyToken(token, AccountDTO.class);
        if (!accountDTO.getId().equals(userId)) {
            AjaxResponse error = AjaxResponse.fail("用户与Token不匹配");
            handleIfFail(error, response);
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    private void handleIfFail(Object object, HttpServletResponse response) throws IOException {
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(object));
        response.getWriter().flush();
    }

}
